﻿// <copyright file="DateTimeConverter.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2008-10-13</date>
// <summary>Value converter to convert from DateTime to strings and back</summary>

namespace Synergist
{
    using System;
    using System.Windows.Data;

    /// <summary>
    /// DateTime value converter
    /// </summary>
    public class DateTimeConverter : IValueConverter
    {
        #region IValueConverter Members

        /// <summary>
        /// Convert from a DateTime to a string
        /// </summary>
        /// <param name="value">a DateTime</param>
        /// <param name="targetType">a string type</param>
        /// <param name="parameter">the formatting parameter for DateTime.ToString()</param>
        /// <param name="culture">the culture to use</param>
        /// <returns>a string representation of the date</returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is DateTime)
            {
                var dt = (DateTime) value;

                if (parameter == null)
                {
                    return dt.ToString(culture);
                }
                else
                {
                    return dt.ToString(parameter as string, culture);
                }
            }

            return null;
        }

        /// <summary>
        /// convert from a string to a DateTime
        /// </summary>
        /// <param name="value">a string to convert to a DateTime type</param>
        /// <param name="targetType">a DateTime type</param>
        /// <param name="parameter">the conversion parameter (unused)</param>
        /// <param name="culture">the culture to use</param>
        /// <returns>a DateTime</returns>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var strValue = value as string;

            if (strValue != null)
            {
                return DateTime.Parse(strValue, culture);
            }

            return null;
        }

        #endregion
    }
}
